<?php

namespace app\common;

use app\notify\controller\Cloud;
use think\cache\driver\Redis;

class Manage extends AbstractAllotManager
{

    public function getYunduoCompanyId()
    {
        // TODO: Implement getYunduoCompanyId() method.
        return "2015";
    }

    public function getYunduoToken()
    {
        // TODO: Implement getYunduoToken() method.
        return "f9e9fc91ec782cb5ebdbb66262b409b1";
    }

    public function getRSAPubKey()
    {
        // TODO: Implement getRSAPubKey() method.
        return "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc+vOEGPUGeVYmhFqIUa9IrVE6\n06dXsFJTFQfXwdW+ZE9DqyNaL0GJNFelm/zfl1M+EHqhEBIqxEH9qj16ipG24vrP\n3qWptOyzz29X7TdB9nUmF9HRh/Z7Ha6voxomhn4bTiOvfaj8CN1pxH2dCYwWiB3o\nB8Kdh/LnHOHW1cFfiwIDAQAB\n-----END PUBLIC KEY-----\n";
    }

    public function isExperimentOn()
    {
        // TODO: Implement isExperimentOn() method.
        return true;
    }

    public function isCustomersToAllot($all_customers)
    {
        // TODO: Implement isCustomersToAllot() method.
        $advertiserList = ['百度搜索', '360搜索', '搜狗', '神马'];
        $accountList = ['公众号', '朋友圈推广', '朋友圈软文'];
        $projectList = ['汉语教师'];
        $cloud=new Cloud();
        $fileList = $cloud->file_val;
        $cusFiled = $cloud->customer;
        $result = array();
        foreach ($all_customers as $v) {
            if (isset($v['belongStatus']) && $v['belongStatus'] == "无归属") {
//                dump($v);
                $data = array();
                foreach ($cusFiled as $vs) {
                    $keys = $vs['keys'];
                    $data[$keys] = isset($v[$keys]) ? $v[$keys] : "";
                }
                $list = db('customer')->where('id', $v['id'])->find();
                //广告商排除
                if (!key_exists('ofc_1', $v) || in_array($v['ofc_1'], $advertiserList)) {
                    continue;
                }
                //推广账户排除
                if (!key_exists('ofc_2', $v) || in_array($v['ofc_2'], $accountList)) {
                    continue;
                }
                //排除项目
                if (!key_exists('ofc_4') || !in_array($v['ofc_4']['value'], $projectList)) {
                    continue;
                }
                if (empty($list)) {
                    $result[] = $v;
                    db('customer')->insert($data);
                }
            } else {
//                dump($v);
                $list = db('customer_1')->where('c_id', $v['uniqueCustomerId'])->find();
                if ($list) {
                    continue;
                }

                $i = 0;
                $j = 1;
                $data = array();
                $data['c_id'] = $v['uniqueCustomerId'];
                foreach ($fileList as $vf) {
                    $i++;
                    $keys = $vf['keys'];
                    $data[$keys] = isset($v[$keys]) ? $v[$keys] : "";
                    if ($i % 45 == 0) {
                        db("customer_" . $j)->insert($data);
                        $j++;
                        $data = array();
                        $data['c_id'] = $v['uniqueCustomerId'];
                    }
                }
                db("customer_" . $j)->insert($data);
//            }
            }
        }
        return $result;
    }

    public function isSaleToAllot($sale)
    {
        // TODO: Implement isSaleToAllot() method.

        return true;
    }

    public function getBucketOfCust($cust, $experiment_percentage)
    {
        // TODO: Implement getBucketOfCust() method.
        $redis = new Redis(config('redis'));
        $inc = $redis->get('customerAutoInc');
        if ($inc) {
            $redis->inc('customerAutoInc');
        } else {
            $redis->inc('customerAutoInc', 1);
        }
        $bucketList = Manage::$EXPERIMENT_BUCKET_SUFFIX;
        $n = $inc % 10;
        if (in_array($n, $bucketList)) {
            //实验桶数据
            return 1;
        } else {
            //对照桶数据
            return 0;
        }
    }

    //尾号为1,6,8为实验桶数据, 即30%
    private static $EXPERIMENT_BUCKET_SUFFIX = array(1, 6, 8);

    public function getExperimentPercentage()
    {
        // 实验桶的百分占比，例如：实验桶30%，则返回30，有限范围[0, 100]
        // TODO: Implement getExperimentPercentage() method.
        return count(Manage::$EXPERIMENT_BUCKET_SUFFIX) * 10;
    }

    public function get_log_file()
    {
        // TODO: Implement get_log_file() method.
        return "./log/mengyue/" . date("Ymd") . ".log";
    }

    public function getAllotRuleInfo()
    {
        // TODO: Implement getAllotRuleInfo() method.
        return ['name' => "汉语教师实时分配", "type" => 0];
    }

    /**
     * 为名片$customer选择一名默认销售人员 预分配销售
     * @param $customer
     * @param $sales
     * @pa ram $bucket string ['exp', 'default']
     * @return mixed Array($customer, $sale)
     */
    public function allotSaleForCustomer($cust, $sales, $bucket)
    {
        // TODO: Implement allotSaleForCustomer() method.
        //预分配销售
        $redis = new Redis(config('redis'));
//        sort($sales,'','')
        array_multisort(array_column($sales, 'saleId'), "ASC", $sales);
        $len = count($sales);
        if ($len <= 0) {
            return false;
        }
        if ($redis->get('last_saler')) {
            $lastSaler = $redis->get('last_saler');
        } else {
            $lastSaler = $sales[0]['saleId'];
        }
        if ($lastSaler == $sales[$len - 1]['saleId']) {
            $lastSaler = $sales[0]['saleId'];
        }
        $sale = array();
        foreach ($sales as $k => $v) {
            $keys = $v['saleId'];
            if ($keys <= $lastSaler) continue;
            if ($redis->get($keys)) {
                $saleRecord = json_decode($saleRecord);
                if ($saleRecord[$bucket] > 0 && $v['saleId'] > $lastSaler) {
                    $sale = $v;
                    break;
                }
            }
        }
        return array($cust, $sale);

    }

    public function getEncryAttr()
    {
        // TODO: Implement getEncryAttr() method.
        return array(
            'fc_4912',
            'phone',
            'qq_number',
            'wechart',
            'contactPhone',
            'idCard',
        );
    }

    public function setData($list)
    {
        // TODO: Implement setData() method.
    }
}